
// import System from '../../node_modules/systemjs' // progress bar

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // 引入进度条样式

import { isNavigationFailure } from 'vue-router'

import store from '../store'
import router from './routes'

// 子系统配置文件
import AppModules from './subprojects'

// const System = require('systemjs')
// 缓存从子工程加载的应用
const cachedModules = {}

router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // 先判断是否登录
  if (!store.getters.isRegister) {
    to.path === '/login' ? next() : next('/login')
    return
  }

  // 取路径中标识子工程前缀的部分, 例如 '/subapp/xxx/index' 其中xxx即路由唯一前缀
  const module = to.path.split('/')[1] || ''
  // 匹配不上子工程信息
  if (!Reflect.has(AppModules, module)) {
    next()
    return
  }

  // 如果已经加载过该子工程的模块，则不再加载，直接取缓存的routes
  if (Reflect.has(cachedModules, module)) {
    next()
    return
  }
  // 如果没有子工程配置信息, 则请求
  let systemModule
  try {
    systemModule = await window.System.import(AppModules[module].js)
  } catch (error) {
    console.warn('路由加载错误', error)
    return
  }
  const { default: application } = systemModule

  // 动态注册Vuex模块
  if (application.store) {
    store.registerModule(application.store.name, application.store.store)
  }

  // 动态添加路由
  if (application && application.routes) {
    const applicationRoutes = application.routes
    Array.isArray(applicationRoutes)
      ? applicationRoutes.forEach((item) => { router.addRoute('content', item) })
      : router.addRoute('content', applicationRoutes)
    // 加缓存
    cachedModules[module] = application
    next(to.fullPath)
    return
  }
  next()
})

router.afterEach((to, from, failure) => {
  // 导航故障
  if (isNavigationFailure(failure)) {
    console.log('导航故障', failure)
  }
  NProgress.done() // finish progress bar
})

router.onError(error => {
  console.log(error, '路由错误')
})

export default router
